package cn.ug.member.mq;

import cn.ug.enums.ProvinceCityEnum;
import cn.ug.enums.WoolLabelEnum;
import cn.ug.feign.IpService;
import cn.ug.feign.MobileAscriptionService;
import cn.ug.feign.WoolCheckService;
import cn.ug.member.mapper.entity.MemberLabel;
import cn.ug.member.service.MemberLabelService;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static cn.ug.config.QueueName.QUEUE_MEMBER_LABEL;
import static cn.ug.util.ConstantUtil.MINUS;
import static cn.ug.util.ConstantUtil.SEMICOLON;

@Component
@RabbitListener(queues = QUEUE_MEMBER_LABEL)
public class MemberLabelReceiver {
    private Log log = LogFactory.getLog(MemberLabelReceiver.class);
    @Autowired
    private MemberLabelService memberLabelService;
    @Autowired
    private WoolCheckService woolCheckService;
    @Autowired
    private MobileAscriptionService mobileAscriptionService;
    @Autowired
    private IpService ipService;
    @Value("${juhe.mobile.ascription.key}")
    private String mobileAscriptionKey;
    @Value("${wool.check.appId}")
    private String woolCheckAppId;
    @Value("${wool.check.appKey}")
    private String woolCheckAppKey;


    @RabbitHandler
    public void process(MemberLabelMQ o) throws JsonProcessingException {
        log.info("MemberLabelReceiver:process.......................");
        if (o == null || StringUtils.isBlank(o.getMemberId()) || o.getType() < 1) {
            return;
        }
        log.info("MemberLabelReceiver:process......................." + JSONObject.toJSONString(o));
        if (o.getType() == 1) {
            // 注册
            if (StringUtils.isBlank(o.getMobile())) {
                return;
            }
            String mobileAscriptionResult = mobileAscriptionService.getMobileAscription(o.getMobile(), mobileAscriptionKey);
            if (StringUtils.isBlank(mobileAscriptionResult)) {
                throw new RuntimeException("获取手机号码：" + o.getMobile() + "，号码归属地出错...");
            }
            MemberLabel memberLabel = new MemberLabel();
            memberLabel.setMemberId(o.getMemberId());
            memberLabel.setMobile(o.getMobile());
            memberLabel.setChannelId(o.getChannelId());
            memberLabel.setChannelName(o.getGetChannelName());
            JSONObject json = JSONObject.parseObject(mobileAscriptionResult);
            if (json.getIntValue("resultcode") == 200) {
                JSONObject finalResult = json.getJSONObject("result");
                if (StringUtils.isNotBlank(finalResult.getString("city"))) {
                    memberLabel.setMobilePlace(finalResult.getString("province") + MINUS + finalResult.getString("city"));
                } else {
                    memberLabel.setMobilePlace(finalResult.getString("province"));
                }
                memberLabel.setMobileCompany(finalResult.getString("company"));
            }

            String woolCheckResult = woolCheckService.woolCheck(o.getMobile(), woolCheckAppId, woolCheckAppKey);
            if (StringUtils.isBlank(woolCheckResult)) {
                throw new RuntimeException("检测手机号码：" + o.getMobile() + ", 羊毛党标签出错...");
            }
            JSONObject woolJson = JSONObject.parseObject(woolCheckResult);
            if (woolJson.getIntValue("code") == 200000) {
                JSONObject finalResult = woolJson.getJSONObject("data");
                memberLabel.setLabel(finalResult.getString("status"));
                if (StringUtils.isNotBlank(finalResult.getString("tag"))) {
                    String[] infos = StringUtils.split(finalResult.getString("tag"), SEMICOLON);
                    if (infos != null && infos.length > 0) {
                        int score = 0;
                        for (String info : infos) {
                            score += WoolLabelEnum.getScoreByMsg(info);
                        }
                        memberLabel.setScore(score);
                    }
                }
            }
            if (!memberLabelService.save(memberLabel)) {
                throw new RuntimeException("保存失败...");
            }
        } else if (o.getType() == 2) {
            // 登陆
            if (StringUtils.isBlank(o.getIp())) {
                return;
            }
            MemberLabel memberLabel = memberLabelService.getLabel(o.getMemberId());
            if (memberLabel == null) {
                return;
            }
            String ipResult = ipService.getIp(o.getIp());
            if (StringUtils.isBlank(ipResult)) {
                throw new RuntimeException("获取ip：" + o.getMobile() + "，地址出错...");
            }
            JSONObject json = JSONObject.parseObject(ipResult);
            if (json.getIntValue("code") == 0) {
                JSONObject finalResult = json.getJSONObject("data");
                String ip1 = finalResult.getString("region") + MINUS + finalResult.getString("city");
                memberLabel.setIp3(memberLabel.getIp2());
                memberLabel.setIp2(memberLabel.getIp1());
                memberLabel.setIp1(ip1);
                String commonIp = "";
                if (StringUtils.equals(memberLabel.getIp1(), memberLabel.getIp2()) || StringUtils.equals(memberLabel.getIp1(), memberLabel.getIp3())) {
                    commonIp = memberLabel.getIp1();
                }

                if (StringUtils.equals(memberLabel.getIp2(), memberLabel.getIp1()) || StringUtils.equals(memberLabel.getIp2(), memberLabel.getIp3())) {
                    commonIp = memberLabel.getIp2();
                }

                if (StringUtils.equals(memberLabel.getIp3(), memberLabel.getIp1()) || StringUtils.equals(memberLabel.getIp3(), memberLabel.getIp2())) {
                    commonIp = memberLabel.getIp3();
                }
                if (StringUtils.isBlank(commonIp)) {
                    commonIp = memberLabel.getIp1();
                }
                memberLabel.setCommonIp(commonIp);
                if (!memberLabelService.save(memberLabel)) {
                    throw new RuntimeException("保存失败...");
                }
            }
        } else if (o.getType() == 3) {
            // 认证绑卡
            if (StringUtils.isBlank(o.getIdcard()) || StringUtils.isBlank(o.getName())) {
                return;
            }
            MemberLabel memberLabel = memberLabelService.getLabel(o.getMemberId());
            if (memberLabel == null) {
                return;
            }
            memberLabel.setName(o.getName());
            memberLabel.setGender(UF.getGender(o.getIdcard()));
            memberLabel.setBornYear(UF.getBirthday(o.getIdcard()).getYear());
            String code = StringUtils.substring(o.getIdcard(), 0, 4);
            String area = ProvinceCityEnum.getAreaByCode(code);
            if (StringUtils.isBlank(area)) {
                area = ProvinceCityEnum.getAreaByCode(StringUtils.substring(o.getIdcard(), 0, 2));
            }
            memberLabel.setNativePlace(area);
            if (!memberLabelService.save(memberLabel)) {
                throw new RuntimeException("保存失败...");
            }
        }
    }
}